package com.heima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.reggie.common.R;
import com.heima.reggie.domain.*;
import com.heima.reggie.service.AddressBookService;
import com.heima.reggie.service.OrderDetailService;
import com.heima.reggie.service.OrdersService;
import com.heima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderDetailController {
    @Resource
    OrdersService ordersService;
    @Resource
    ShoppingCartService shoppingCartService;
    @Resource
    OrderDetailService orderDetailService;
    @Resource
    AddressBookService addressBookService;

    @PostMapping("/submit")
    @Transactional
    public R<String> submit(@RequestBody Orders orders, HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        BigDecimal amounts = BigDecimal.ZERO;
        for (int i = 0; i < list.size(); i++) {
            ShoppingCart shoppingCart = list.get(i);
            BigDecimal amount = shoppingCart.getAmount();
            Integer number = shoppingCart.getNumber();
            BigDecimal numberBigDecimal = new BigDecimal(number.toString());
            BigDecimal total = amount.multiply(numberBigDecimal);
            amounts = amounts.add(total);
        }
        orders.setAmount(amounts);
        Long addressBookId = orders.getAddressBookId();
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook :: getId , addressBookId);
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
        String consignee = addressBook.getConsignee();
        orders.setConsignee(consignee);
        String detail = addressBook.getDetail();
        orders.setAddress(detail);
        String phone = addressBook.getPhone();
        orders.setPhone(phone);
        UUID uuid = UUID.randomUUID();
        orders.setNumber(uuid.toString());
//        String userName = (String) session.getAttribute("user");
//        orders.setUserName(userName);

        ordersService.save(orders);
        log.info("shoppingList======{}", list);
        List<OrderDetail> orderDetails = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            ShoppingCart shoppingCart = list.get(i);
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setAmount(shoppingCart.getAmount());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetails.add(i,orderDetail);
        }
        Long ordersId = orders.getId();
        for (OrderDetail orderDetail : orderDetails) {
            orderDetail.setOrderId(ordersId);
        }
        log.info("orderDetail==========={}", orderDetails);
        orderDetailService.saveBatch(orderDetails);

        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart :: getUserId , userId);
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper1);

        return R.success("支付成功");

    }

    @GetMapping("/userPage")
    public R<Page> userPage(Integer page , Integer pageSize , HttpSession session){
        Page<Orders> page1 = new Page<>(page,pageSize);
        Long userId = (Long) session.getAttribute("user");
        if(pageSize == 1){
            LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
            ordersLambdaQueryWrapper.eq(Orders::getUserId , userId).orderByDesc(Orders::getCheckoutTime).getSqlFirst();
            ordersService.page(page1,ordersLambdaQueryWrapper);
            return R.success(page1);
        }
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders :: getUserId , userId);
        ordersService.page(page1, ordersLambdaQueryWrapper);
        return R.success(page1);
    }

    @GetMapping("/page")
    public R<Page> page(Integer page , Integer pageSize , String number , String beginTime , String endTime){

        Page<Orders> ordersPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(number != null ,Orders::getNumber , number);
        if(StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime)) {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime begin = LocalDateTime.parse(beginTime, dateTimeFormatter);
            LocalDateTime end = LocalDateTime.parse(endTime, dateTimeFormatter);
            ordersLambdaQueryWrapper.between(Orders::getOrderTime ,begin,end);
        }

        ordersService.page(ordersPage , ordersLambdaQueryWrapper);
        return R.success(ordersPage);
    }
}
